package org.agent.aigccore.core.service.user;

import jakarta.annotation.Resource;
import org.agent.aigccore.basic.exception.AuthException;
import org.agent.aigccore.basic.exception.UserException;
import org.agent.aigccore.model.po.UserInfoPO;
import org.agent.aigccore.utils.JwtUtil;
import org.agent.aigccore.utils.PasswordUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AuthService {
    
    @Resource
    private UserService userService;
    
    @Resource
    private JwtUtil jwtUtil;
    
    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return JWT令牌
     * @throws AuthException 登录失败异常
     */
    public String login(String username, String password) throws AuthException {
        return login(username, password, false);
    }
    
    /**
     * 用户登录（支持记住我）
     *
     * @param username 用户名
     * @param password 密码
     * @param rememberMe 是否记住我
     * @return JWT令牌
     * @throws AuthException 登录失败异常
     */
    public String login(String username, String password, boolean rememberMe) throws AuthException {
        try {
            // 根据用户名查找用户
            UserInfoPO userInfoPO = userService.loadByUsername(username);
            
            if (userInfoPO == null) {
                throw new AuthException("USER_NOT_FOUND", "用户不存在");
            }
            
            // 验证密码
            if (!PasswordUtil.matches(password, userInfoPO.getPassword())) {
                throw new AuthException("INVALID_PASSWORD", "密码错误");
            }
            
            // 检查用户状态
            if (!"NORMAL".equals(userInfoPO.getStatus())) {
                throw new AuthException("USER_DISABLED", "用户账户已被禁用");
            }
            
            // 更新最后登录时间
            userService.updateLastLoginTime(userInfoPO.getUserId());
            
            // 生成JWT令牌
            return jwtUtil.generateToken(userInfoPO, rememberMe);
        } catch (AuthException e) {
            throw e;
        } catch (Exception e) {
            throw new AuthException("LOGIN_FAILED", "登录失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 用户注册
     *
     * @param userInfoPO 用户信息
     * @return 是否注册成功
     * @throws UserException 注册失败异常
     */
    public boolean register(UserInfoPO userInfoPO) throws UserException {
        try {
            // 参数校验
            if (userInfoPO.getUsername() == null || userInfoPO.getUsername().trim().isEmpty()) {
                throw new UserException("INVALID_USERNAME", "用户名不能为空");
            }
            
            if (userInfoPO.getPassword() == null || userInfoPO.getPassword().trim().isEmpty()) {
                throw new UserException("INVALID_PASSWORD", "密码不能为空");
            }
            
            // 检查用户名是否已存在
            if (userService.loadByUsername(userInfoPO.getUsername()) != null) {
                throw new UserException("USERNAME_EXISTS", "用户名已存在");
            }
            
            // 检查邮箱是否已存在
            if (userInfoPO.getEmail() != null && !userInfoPO.getEmail().trim().isEmpty()) {
                if (userService.loadByEmail(userInfoPO.getEmail()) != null) {
                    throw new UserException("EMAIL_EXISTS", "邮箱已存在");
                }
            }
            
            // 设置用户ID
            userInfoPO.setUserId(java.util.UUID.randomUUID().toString());
            
            // 设置默认角色为普通用户
            userInfoPO.setRole("USER");
            
            // 设置默认状态为正常
            userInfoPO.setStatus("NORMAL");
            
            // 设置创建时间
            userInfoPO.setGmtCreate(new Date());
            
            // 插入用户信息
            int result = userService.insert(userInfoPO);
            
            return result > 0;
        } catch (UserException e) {
            throw e;
        } catch (Exception e) {
            throw new UserException("REGISTER_FAILED", "注册失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 修改密码
     *
     * @param username 用户名
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 是否修改成功
     * @throws AuthException 修改失败异常
     */
    public boolean changePassword(String username, String oldPassword, String newPassword) throws AuthException {
        try {
            // 参数校验
            if (username == null || username.trim().isEmpty()) {
                throw new AuthException("INVALID_USERNAME", "用户名不能为空");
            }
            
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                throw new AuthException("INVALID_OLD_PASSWORD", "旧密码不能为空");
            }
            
            if (newPassword == null || newPassword.trim().isEmpty()) {
                throw new AuthException("INVALID_NEW_PASSWORD", "新密码不能为空");
            }
            
            // 根据用户名查找用户
            UserInfoPO userInfoPO = userService.loadByUsername(username);
            
            if (userInfoPO == null) {
                throw new AuthException("USER_NOT_FOUND", "用户不存在");
            }
            
            // 验证旧密码
            if (!PasswordUtil.matches(oldPassword, userInfoPO.getPassword())) {
                throw new AuthException("INVALID_OLD_PASSWORD", "旧密码错误");
            }
            
            // 检查新密码是否与旧密码相同
            if (PasswordUtil.matches(newPassword, userInfoPO.getPassword())) {
                throw new AuthException("SAME_PASSWORD", "新密码不能与旧密码相同");
            }
            
            // 重置密码
            int result = userService.resetPasswordByUsername(username, newPassword);
            
            if (result <= 0) {
                throw new AuthException("PASSWORD_UPDATE_FAILED", "密码更新失败");
            }
            
            return true;
        } catch (AuthException e) {
            throw e;
        } catch (Exception e) {
            throw new AuthException("CHANGE_PASSWORD_FAILED", "修改密码失败: " + e.getMessage(), e);
        }
    }
}